package com.xwt.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xwt.web.dao.AuthorityRepository;
import com.xwt.web.entity.Authority;

@RestController
@RequestMapping("/admin")

public class AdminController {
	@Autowired
	private AuthorityRepository authorityDao;

	@RequestMapping("/addAuthority")
	public List<Authority> addAuthority(@RequestBody Authority authority) {
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		authority.setUsername(username);
		List<Authority> oldlist = authorityDao.findByUsername(username);
		for(int i=0;i<oldlist.size();i++) {
			if(authority.getAuthority().equals(oldlist.get(i).getAuthority())) {
				return null;
			}
		}
		authorityDao.save(authority);
		List<Authority> newlist = authorityDao.findByUsername(username);
		return newlist;

	}
	/**
	 * 使用标签进行权限注解配置<br>
	 * https://blog.csdn.net/luenxin/article/details/50159311
	 * @param username
	 * @return
	 */
	@PreAuthorize("hasAuthority('ADMIN')")
	@RequestMapping("/findall")
	public List<Authority> findAllAuthority(@RequestParam(value = "username") String username) {
		List<Authority> newlist = authorityDao.findByUsername(username);
		return newlist;
	}
}
